# from lxml import etree
# from lxml import html
# etree=html.etree
import os, time, subprocess
from common.qr_code import QRCodeX
from appium import webdriver


class AndroidUI:
    #    #com.sofmit.gzsk/com.sofmit.gzsk.mvp.ui.splash.SplashActivity
    #      com.bluephone/com.bluecart.activity.System3Activity
    # adb shell am start -n com.bluephone/com.bluecart.activity.SplashActivity

    """
    {
{
        "platformName" = "Android"
        "platformVersion" = "7.1.1"
        "deviceName" = "Appium"
        "appPackage" = "com.bluephone"
        "appActivity" = "com.bluecart.activity.SplashActivity"
        "udid" = "MT66-2XA-AG06159"
        "unicodeKeyboard" = "True"
}
}
    """
    driver = None  # 类级变量，跟随类内存空间而不随实例内存空间

    def __init__(self, wait=0.1):
        self.wait = wait
        self.now_time = time.strftime('%Y-%m-%d %H:%M:%S')
        self.log_name = time.strftime("log_%Y%m%d_%H%M%S.csv")
        self.result_name = time.strftime("result_%Y%m%d_%H%M%S.csv")
        self.cleaner = "9999010001A1001"  # 赵清理人二维码
        self.waike = "9999010001B1001"  # 外科
        self.qianhushi = "9999010001A2001"  # 钱护士
        self.zancunjian = "9999010001B2001"  # 暂存间
        self.sunchuzhi = "9999010001A3001"  # 孙处置

    # 实例化一个WebDriver，供其他所有测试脚本调用，并确保返回唯一的一个Driver实例（单例模式）
    @classmethod  # 类方法：直接通过类名调用，不需要通过实例来调用的方法，与@staticmethod类似
    def get_webdriver(cls):
        if cls.driver == None:
            desired_caps = {}  # 定义webdriver的兼容性设置字典对象用于设置核心参数
            desired_caps['platformName'] = 'Android'  # 指定测试Android平台
            # desired_caps['platformVersion'] = '7.0'  # 指定移动端的版本号，出码一体白色
            desired_caps['platformVersion'] = '8.1.0'  # 指定移动端的版本号，出码一体黑色
            # desired_caps['platformVersion'] = '5.1'  # 出码分离 黑色       指定移动端的版本号
            # desired_caps['platformVersion'] = '5.1.1'  # 出码分离 黑色       指定移动端的版本号
            # desired_caps['platformVersion'] = '10'  # huawei       指定移动端的版本号
            desired_caps['deviceName'] = 'Appium'  # 指定设备名称
            # desired_caps['appPackage'] = 'com.rjkj.medicalhighvalue'  # 指定要启动的包
            # desired_caps['appActivity'] = '.activity.SplashActivity'
            desired_caps['appPackage'] = 'com.bluephone'  # 指定要启动的包
            desired_caps['appActivity'] = 'com.bluecart.activity.SplashActivity'  # 指定启动的主类程序
            # desired_caps['appActivity'] = 'com.bluecart.activity.LoginActivity'  # 指定启动的主类程序
            desired_caps['noReset'] = True
            desired_caps['unicodeKeyboard'] = True  # 可以输入中文
            # desired_caps['udid'] = '0123456789ABCDEF'  # 出码一体白色   指定设备编号(adb devices输出结果)
            # desired_caps['udid'] = '660320040026'  # 出码一体黑色   指定设备编号(adb devices输出结果)
            desired_caps['udid'] = 'MT66-2XA-BB05175'  # 出码分离  黑色    指定设备编号(adb devices输出结果)
            # desired_caps['udid'] = 'NZ53MMM861'  # 出码分离  黑色    指定设备编号(adb devices输出结果)
            # desired_caps['udid'] = '8KE5T19830020100'  # huawei   指定设备编号(adb devices输出结果)
            # desired_caps['udid'] = '192.168.2.133:5555'  # 指定设备编号(adb devices输出结果)
            # com.bluephone', 'com.bluecart.activity.SplashActivity
            cls.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
            cls.driver.implicitly_wait(20)   #隐式等待时间5秒
            # time.sleep(6)

        return cls.driver

    # 判断元素是否存在
    # @classmethod
    # def isElement(cls, identifyBy, body):
    #     '''
    #     Determine whether elements exist
    #     Usage:
    #     isElement(By.XPATH,"//a")
    #     '''
    #     # time.sleep(1)
    #     try:
    #         if identifyBy == "id":
    #             # self.driver.implicitly_wait(60)
    #             cls.driver.find_element_by_id(body)
    #         elif identifyBy == "xpath":
    #             # self.driver.implicitly_wait(60)
    #             cls.driver.find_element_by_xpath(body)
    #         elif identifyBy == "class":
    #             cls.driver.find_element_by_class_name(body)
    #         elif identifyBy == "link text":
    #             cls.driver.find_element_by_link_text(body)
    #         elif identifyBy == "partial link text":
    #             cls.driver.find_element_by_partial_link_text(body)
    #         elif identifyBy == "name":
    #             cls.driver.find_element_by_name(body)
    #         elif identifyBy == "tag name":
    #             cls.driver.find_element_by_tag_name(body)
    #         elif identifyBy == "css selector":
    #             cls.driver.find_element_by_css_selector(body)
    #         elif identifyBy == "text":
    #             cls.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{body}")').click()
    #
    #         return True
    #     except:
    #         return False

    #
    #
    #
    #
    # 判断元素是否存在

    def isElement(self, identifyBy, body):
        '''
        Determine whether elements exist
        Usage:
        isElement(By.XPATH,"//a")
        '''
        # time.sleep(1)
        flag = None
        try:
            if identifyBy == "id":
                # self.driver.implicitly_wait(60)
                self.driver.find_element_by_id(body)
            elif identifyBy == "xpath":
                # self.driver.implicitly_wait(60)
                self.driver.find_element_by_xpath(body)
            elif identifyBy == "class":
                self.driver.find_element_by_class_name(body)
            elif identifyBy == "link text":
                self.driver.find_element_by_link_text(body)
            elif identifyBy == "partial link text":
                self.driver.find_element_by_partial_link_text(body)
            elif identifyBy == "name":
                self.driver.find_element_by_name(body)
            elif identifyBy == "tag name":
                self.driver.find_element_by_tag_name(body)
            elif identifyBy == "css selector":
                self.driver.find_element_by_css_selector(body)
            elif identifyBy == "text":
                self.driver.find_element_by_android_uiautomator(f'new UiSelector().textContains("{body}")').click()
            flag = True
        except:
            flag = False
        finally:
            return flag

    # 判断元素是否存在
    @classmethod
    def is_element_exist(self, element):
        source = self.driver.page_source
        # print(source)
        if element in source:
            return True
        else:
            return False

    # 扫码
    @classmethod
    def scan(cls, x):
        os.system("adb shell am broadcast -a android.intent.ACTION_DECODE_DATA --es barcode_string %s" % x)
        time.sleep(3)

    # 清理人登录
    @classmethod
    def login(cls, x):
        cls.scan(x)

    # 返回按钮
    @classmethod
    def back_button(cls):
        os.popen('adb shell input keyevent "KEYCODE_BACK"')
        time.sleep(0.1)

    # 截图
    @classmethod
    def capture(cls):
        filename = time.strftime("%Y%m%d_%H%M%S")
        os.system('adb shell screencap -p /sdcard/%s.png' % filename)
        path = os.path.abspath(r"D:\rj自动化\GUI_Appium\screen")
        # path=os.path.abspath("../screen")
        print(path)
        os.system("adb pull /sdcard/%s.png %s " % (filename, path))
        time.sleep(0.1)

    # 一直截图
    # def capture(self):
    #     while(True):
    #         filename = time.strftime("%Y%m%d_%H%M%S")
    #         os.system('adb shell screencap -p /sdcard/%s.png'%filename)
    #         path=os.path.abspath("../screen")
    #         print(path)
    #         os.system("adb pull /sdcard/%s.png %s "%(filename,path))
    #         time.sleep(3)

    # 写日志
    # @classmethod
    #
    # def write_log(self,operation,x,y,content='None'):
    #     with open("../log/"+self.log_name,"a+") as file:
    #         line='%s,%d,%d,%s\n'% (operation,x,y,content)
    #         file.write(line)

    # 写结果

    def write_result(self, operation, result):
        # with open(r"D:\rj自动化\GUI_Appium\report\2"+self.result_name,"a+") as file:
        with open(r"D:\rj自动化\GUI_Appium\report\测试.csv", "a") as file:
            # with open("../report/"+self.result_name,"a+") as file:
            line = '%s,%s,%s\n' % (operation, result, self.now_time)
            file.write(line)

    # @classmethod
    # def write_result(cls,operation,result):
    #     now_time = time.strftime("%Y-%m-%d %H:%M:%S")
    #     with open('../report/测试.csv', mode='a+', encoding='utf-8') as file:
    #         file.write("%s,%s,%s\n" % (operation,result,now_time))

    #
    #     now_time = time.strftime('%Y%m%d_%H%M%S')
    #     # with open(r"D:\rj自动化\GUI_Appium\report\2"+self.result_name,"a+") as file:
    #     with open(r"../report/测试.csv","a") as file:
    #     # with open("../report/"+self.result_name,"a+") as file:
    #         line='%s,%s,%s\n'% (operation,result,now_time)
    #         file.write(line)
    # #
    # def write_result(self,operation,result):
    #     with open("../report/"+self.result_name,"a+") as file:
    #         line='%s,%s,%s\n'% (operation,result,self.now_time)
    #         file.write(line)

    # def read_csv(self):
    #     with open("D:\pythoWorkspace\\framework_by_qiang\data\\user.csv", encoding='utf-8') as file:
    #         content = file.readlines()
    #         list = []
    #         for line in content:
    #
    #             # 去掉#开头的
    #             if line.startswith('#'):
    #                 continue
    #             dict = {}
    #             dict['username'] = line.strip().split(',')[0]
    #             dict['password'] = line.strip().split(',')[1]
    #             dict['result'] = line.strip().split(',')[2]
    #             # print(dict)
    #             # print(line)
    #             list.append(dict)
    #         return list

    def read_csv(self, filepath):
        # os.path.exists判断文件是否存在
        if os.path.exists(filepath):
            with open(filepath, encoding='utf-8') as file:
                content = file.readlines()
            key_list = []
            data_list = []
            for row in range(len(content)):
                # 跳过以#号开头的行及空行
                if content[row].startswith('#') or content[row] == '\n':
                    continue
                elif key_list == []:
                    key_list = content[row].strip().split(',')
                else:
                    value_list = content[row].strip().split(',')
                    info = dict(zip(key_list, value_list))
                    data_list.append(info)
            return data_list
        else:
            return False


if __name__ == '__main__':
    driver = AndroidUI()
    driver.get_webdriver().find_element_by_id('com.bluephone:id/systemSet1').click()
    # code=QRCodeX()
    # AndroidUI().write_result("点击首次使用", "失败")
    # AndroidUI.capture()
    # driver.write_result("ch", 'sccc')
    # driver.capture()
    # driver.capture()
    # driver.stop()
    # driver.scan(code.zhaoqingli)
    # driver.scan(code.waike)
    # driver.scan(code.qianhushi)
    # driver.scan(code.zancunjian)
    # driver.scan(code.sunchuzhi)
